package com.example.monitoringsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.monitoringsystem.bean.Medicine;
import com.example.monitoringsystem.bean.Prescribe;
import com.example.monitoringsystem.bean.Prescription;
import com.example.monitoringsystem.mapper.PrescribeMapper;
import com.example.monitoringsystem.mapper.PrescriptionMapper;
import com.example.monitoringsystem.service.MedicineService;
import com.example.monitoringsystem.service.PrescriptionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PrescriptionServiceImpl implements PrescriptionService {

    @Autowired
    private PrescriptionMapper prescriptionMapper;

    @Autowired
    private PrescribeMapper prescribeMapper;

    @Autowired
    private MedicineService medicineService;

    //显示已有处方
    @Override
    public Map showPrescription(int doctorId, int patientId) {
        Map<String,Object> map = new HashMap<>();
        //根据病人id查询开的处方
        QueryWrapper<Prescribe> wrapper = new QueryWrapper<Prescribe>();
        wrapper.eq("doctor_id", doctorId);
        wrapper.eq("patient_id",patientId);
        List<Prescribe> prescribes = prescribeMapper.selectList(wrapper);
        List<Prescription> prescriptions = new ArrayList<>();
        List<Medicine> medicines = new ArrayList<>();
        //返回每一条处方
        QueryWrapper<Prescription> wrapper1 = new QueryWrapper<>();
        for(int i = 0;i<prescribes.size();i++){
            wrapper1.eq("prescription_id",prescribes.get(i).getPrescriptionId());
            prescriptions.add(prescriptionMapper.selectOne(wrapper1));
            Medicine medicine = medicineService.showMedicine(prescriptionMapper.selectOne(wrapper1));
            medicines.add(medicine);
            //根据每一条处方查询药物信息
            wrapper1.clear();
        }
        map.put("prescriptions", prescriptions);
        map.put("medicines", medicines);
        return map;
    }

    //医生开单条处方
    @Override
    public void prescribe(Prescription prescription){
        prescriptionMapper.insert(prescription);
    }

    @Override
    public Prescription findPrescriptionById(int prescriptionId) {
        QueryWrapper<Prescription> wrapper = new QueryWrapper<>();
        wrapper.eq("prescription_id",prescriptionId);
        return prescriptionMapper.selectOne(wrapper);

    }
}
